use crate::common::db::DatabaseState;
use crate::common::{self, ApiResult};
use axum::extract::Json;
use axum::extract::State;
use axum::http::header::HeaderMap;
use axum::routing::get;
use axum::Router;
use axum_extra::extract::Query;
use mysql::prelude::*;
use mysql::*;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};

pub async fn route(
    router: Router<Arc<Mutex<DatabaseState>>>,
    path: String,
) -> Router<Arc<Mutex<DatabaseState>>> {
    router.route(format!("{}/list", path).as_str(), get(list))
}

#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct ArticleListParam {
    page: Option<usize>,
    limit: Option<usize>,
    importance: Option<usize>,
    sort: Option<String>,
    title: Option<String>,
    r#type: Option<String>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct Article {
    id: usize,
    timestamp: usize,
    author: String,
    reviewer: String,
    title: String,
    content_short: String,
    content: String,
    forecast: f64,
    importance: i32,
    #[serde(rename = "type")]
    atype: String,
    status: String,
    display_time: String,
    comment_disabled: u8,
    pageviews: u32,
    image_uri: String,
    platforms: Vec<String>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct ArticleListData {
    total: usize,
    items: Vec<Article>,
}
//article/list?page=1&limit=20&sort=%2Bid
pub async fn list(
    State(db_state): State<Arc<Mutex<DatabaseState>>>,
    Query(param): Query<ArticleListParam>,
    headers: HeaderMap,
) -> Json<ApiResult<ArticleListData>> {
    if headers.contains_key("x-token") {
        let x_token = headers["x-token"].to_str().unwrap();
        println!("\x1b[31marticle/list token is\x1b[0m \"{}\"", x_token);
        let mut conn = db_state.lock().unwrap().pool.get_conn().unwrap();
        let result: Option<(usize, String, String)> = conn.exec_first(
            "select `user`.`id`,`user`.`nick`,`user`.`name` from `token` join `user` on `token`.`user_id`=`user`.`id` where `token`=:token and `expire`>unix_timestamp(now())",
            params! {"token" => x_token},
        ).unwrap();
        match result {
            Some((id, user_name, name)) => {
                println!("user \x1b[32m#{}\x1b[0m {}【{}】", id, user_name, name);
                println!("param {:?}", param);
                let res = vec![
                    Article {
                        id: 100,
                        timestamp: 1724758793,
                        author: "Ronald".to_string(),
                        reviewer: "Kevin".to_string(),
                        title: "Tddoxnoio Lzmsqond Rndvs Bfkacrqit Hrfbe Pmsyuic Nxj Zbqs Mck".to_string(),
                        content_short: "mock data".to_string(),
                        content: "<p>I am testing data, I am testing data.</p><p><img src=\"https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943\"></p>".to_string(),
                        forecast: 70.35,
                        importance: 2,
                        atype: "CN".to_string(),
                        status: "published".to_string(),
                        display_time: "1983-05-24 09:25:20".to_string(),
                        comment_disabled: 1,
                        pageviews: 3643,
                        image_uri: "https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3".to_string(),
                        platforms: vec!("a-platform".to_string()),
                    },
                    Article {
                        id: 101,
                        timestamp: 1724778793,
                        author: "金庸".to_string(),
                        reviewer: "Kevin".to_string(),
                        title: "神雕侠侣".to_string(),
                        content_short: "mock data".to_string(),
                        content: "<p>I am testing data, I am testing data.</p><p><img src=\"https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943\"></p>".to_string(),
                        forecast: 70.35,
                        importance: 5,
                        atype: "CN".to_string(),
                        status: "published".to_string(),
                        display_time: "1983-05-24 09:25:20".to_string(),
                        comment_disabled: 1,
                        pageviews: 3643,
                        image_uri: "https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3".to_string(),
                        platforms: vec!("a-platform".to_string()),
                    }
                ];
                Json(ApiResult {
                    code: common::API_SUCCESS,
                    data: Some(ArticleListData {
                        total: 1,
                        items: res,
                    }),
                    message: None,
                })
            }
            None => Json(ApiResult {
                code: common::ERROR_BAD_TOKEN,
                data: None,
                message: Some("bad token".to_string()),
            }),
        }
    } else {
        Json(ApiResult {
            code: common::ERROR_BAD_PARAMS,
            data: None,
            message: Some("bad params".to_string()),
        })
    }
}
